package io.capsulode.tunnel.blockrepo;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;

@Controller
@RequestMapping("/proxies")
public class ProxyProviderController {
    private static final String YAML_CONTENT_TYPE = "text/vnd.yaml;charset=UTF-8";
    private static final MediaType TEXT_PLAIN = MediaType.parseMediaType("text/plain;charset=UTF-8");

    private final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
    private final ProxyRepository repository;

    public ProxyProviderController(ProxyRepository proxyRepository) {
        this.repository = proxyRepository;
    }

    public static final class ProxiesResponse {
        private final Collection<ProxyDefinition> proxies;

        ProxiesResponse(Collection<ProxyDefinition> proxies) {
            this.proxies = proxies;
        }

        public Collection<ProxyDefinition> getProxies() {
            return proxies;
        }
    }

    @GetMapping
    public void list(ServletWebRequest webRequest, HttpServletResponse response) throws IOException {
        if (webRequest.checkNotModified(repository.etag(), repository.lastModified())) {
            return;
        }
        response.setContentType(YAML_CONTENT_TYPE);
        response.setHeader("Content-Disposition", "attachment;filename=proxies.yaml");
        try (ServletOutputStream out = response.getOutputStream()) {
            repository.write(out);
            out.flush();
        }
    }

}
